# 导包
import yaml
import os
from configs.setting import FILE_PATH
from unit_tools.log_util.recordlog import logs



def read_yaml(yaml_path):

    try:
        testcase_list = []
        with open(yaml_path, 'r', encoding='utf-8') as file:
            data = yaml.safe_load(file)
            if len(data) <= 1:
                yaml_data = data[0]
                base_info = yaml_data.get('baseInfo')
                print(base_info)
                for ts in yaml_data.get('testCase'):
                    params = [base_info, ts]
                    testcase_list.append(params)
                return testcase_list
            else:
                return data


    except UnicodeDecodeError:
        logs.error(f"{yaml_path}文件编码格式错误，--尝试使用utf-8去解码YAML文件发送错误，请确保你的yaml文件是utf-8格式！")
    except yaml.YAMLError as e:
        logs.error(f'Error：读取yaml文件失败，请检查格式 -{yaml_path}，异常原因：{e}')
    except Exception as e:
        logs.error(f"读取{yaml_path}文件时出现异常，原因：{e}")


def write_yaml(value):
    file_path = FILE_PATH['extract']
    if not os.path.exists(file_path):
        with open(file_path, 'w'):
            pass

    file = None

    try:
        file = open(file_path, 'a', encoding='utf-8')
        if isinstance(value, dict):
            write_data = yaml.dump(value, allow_unicode=True, sort_keys=False)
            file.write(write_data)
        else:
            logs.warning("写入的数据必须为字典类型！")
    except Exception as e:
        logs.error(f"写入yaml文件出现异常，原因：{e}")
    finally:
        file.close()



def clear_yaml():

    with open(FILE_PATH['extract'], 'w', encoding='utf-8') as f:
        f.truncate()


def get_extract_yaml(node_name, sub_node_name=None):

    file_path = FILE_PATH['extract']
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            extract_data = yaml.safe_load(file)
            if sub_node_name is None:
                return extract_data[node_name]
            else:
                return extract_data.get(node_name, {}).get(sub_node_name, {})
    except yaml.YAMLError as e:
        logs.error(f'Error：读取yaml文件失败，请检查格式 -{file_path}，异常原因：{e}')
    except Exception as e:
        logs.error(f'Error：未知异常 - 原因：{e}')


if __name__ == '__main__':
    res = read_yaml('../../testcase/userManager/adduser.yaml')